var condition = "";

var page = 1; //默认页数
var pageSize = 10; //每页条数
var total = 0; //总条数
//分页方法
function paging(page, pageSize, total) {
	page = Number(page);

	//最大页数
	var maxPage = Math.ceil(total / pageSize) || 1;
	if(page > maxPage) {
		//取值不能超过maxPage
		page = Math.min(page, maxPage);
		tiaozhuan(param, page, pageSize, condition);
	} else if(page < 1) {
		//取值不能小于1
		page = Math.max(page, 1);
		tiaozhuan(param, page, pageSize, condition);
	} else {
		//	当前页数
		$('.ui-paging-count').val(page);
		//首页的置灰处理
		$('.js-page-first').removeClass('ui-pager-disabled');
		//上一页
		$('.js-page-prev').removeClass('ui-pager-disabled').attr("data-page", page - 1);
		//下一页
		$('.js-page-next').removeClass('ui-pager-disabled').attr("data-page", page + 1);
		//最末页
		$('.js-page-last').removeClass('ui-pager-disabled').attr("data-page", maxPage);
		//总页数显示
		$('.js-page-total').text(maxPage);

		//当前显示多少页的处理
		$(".ui-select-pagesize").val(pageSize);
		//第一页的处理
		if(page == 1) {
			$(".js-page-first").addClass('ui-pager-disabled').attr("data-page", "");
			$(".js-page-prev").addClass('ui-pager-disabled').attr("data-page", "");
		}
		if(page == maxPage) {
			//最后一页的处理
			$(".js-page-last").addClass('ui-pager-disabled').attr("data-page", "");
			$(".js-page-next").addClass('ui-pager-disabled').attr("data-page", "");
		}
	}

};
//下拉选择分页条数的操作
$('.ui-select-pagesize').on("change", function() {
	pageSize = $(this).val();
	tiaozhuan(param, page, pageSize, condition);
});

//跳转到X页  blur
$(".ui-paging-count").on("blur", function() {
	page = $(this).val();
	tiaozhuan(param, page, pageSize, condition);
});

//上一页，下一页，首页，最末页的跳转
$('.ui-pager').on("click", function() {
	page = $(this).attr("data-page");
	tiaozhuan(param, page, pageSize, condition);
});

//角色名查找
$('.clickFunc').on("click", function() {
	condition = $('#searchRalename').val();
	tiaozhuan(param, page, pageSize, condition);
});

function tiaozhuan(param, page, pageSize, condition) {
	var html = "";
	method = "post";
	datas = { page: page, pageSize: pageSize, username: condition };
	getAgentMsg(param, method, datas);
//	console.log(dataResult);

	for(var i = 0; i < dataResult.data.rows.length; i++) {
		var isOpen = "";
		if(dataResult.data.rows[i].status == 1) {
			isOpen = "open";
		}
		html += "<tr>";
		html += "<td><div class='switch " + isOpen + "' data-status='" + dataResult.data.rows[i].status + "' data-id='" + dataResult.data.rows[i].id + "'></div></td>";
		html += "<td>" + dataResult.data.rows[i].id + "</td>";
		html += "<td>" + dataResult.data.rows[i].adComapyName + "</td>";
		html += "<td>" + dataResult.data.rows[i].username + "</td>";
		html += "<td>" + dataResult.data.rows[i].concat + "</td>";
		html += "<td>" + dataResult.data.rows[i].phone + "</td>";
		var passT = "";
		var textCol = "";
		//text-danger text-success text-warning
		if(dataResult.data.rows[i].userStatus==3){
			passT = "审核失败";
			textCol="text-danger";
		}else if(dataResult.data.rows[i].userStatus==2){
			passT = "审核通过";
			textCol="text-success";
		}else{
			passT = "待审核";
			textCol="text-warning";
		}
		html += "<td><p class='"+textCol+"'>"+passT+"</p></td>";
		html += "<td><a href='javascript:void(0);' data-uid='" + dataResult.data.rows[i].id + "' onclick='showProfits(this);'>"+dataResult.data.rows[i].profit+"</a>%</td>";
		html += "<td><a href='javascript:void(0)' data-uid='" + dataResult.data.rows[i].id + "' onclick='showRePwd(this)'>重置密码</a>&nbsp;&nbsp;";
		html += "<a href='javascript:void(0)' data-uid='" + dataResult.data.rows[i].id + "' onclick='getRoleListE(this)'>编辑</a>&nbsp;&nbsp;";
		html += "</td>";
		html += "</tr>";
//		<td>
//			<a href="javascript:;" ng-click="showQua(item.id)">资质上传</a>
//			&nbsp;&nbsp;
//			<a href="javascript:;" ng-click="showRePwd(item.id)">重置密码</a>
//			&nbsp;&nbsp;
//			<a href="javascript:;" ng-click="updateAdv(item.id,item.canSetPremiun)">编辑</a>
//			&nbsp;&nbsp;
//			<a href="javascript:;" ng-click="updateDomain(item.id)">绑定域名</a>
//		</td>
	
	}
	$(".roleList").html(html);
	//之后处理分页
	total = dataResult.data.total;
	paging(page, pageSize, total);
		$(".switch ").on("click", function() {
			var userStatus = $(this).attr("data-status");
			if(userStatus == 1) {
				userStatus = 0;
			} else {
				userStatus = 1;
			}
			$(this).attr("data-status", userStatus);
			$(this).toggleClass("open");
			//执行修改状态的ajax
			var param2 = "/sys/updateStatus";
			var method2 = "post";
			var userId = $(this).attr("data-id");
	
			var datas2 = { userId: userId, userStatus: userStatus};
			getAgentMsg2(param2, method2, datas2);
			layer.msg(dataResult2.msg);
	
		});

}

var datauId = "";

//打开重置密码模态框
function showRePwd(obj){
	datauId = $(obj).attr("data-uid");
	$("#layui-layer7").show();
	$('#popLayer').show();
}

//关闭重置密码模态框
$(".closeRePwd").on("click",function(){
	$("#layui-layer7").hide();
	$('#popLayer').hide();
});

//重置密码确定按钮
$(".resetAdvPWD").on("click",function(){
	$(this).attr("disabled",true).css("background","#BBBBBB");
	    //background: #53bf8b;
	var newPassword = $("#advPwdpassWord").val();
	var resetPassword = $("#advPwdpassWord2").val();
	if(!newPassword || !resetPassword){
		layer.msg("请输入新密码");
		$(this).attr("disabled",false).css("background","#53bf8b");
		return false;
	}
	if(newPassword != resetPassword){
		layer.msg("新旧密码不一致");
		$(this).attr("disabled",false).css("background","#53bf8b");
		return false;
	}
	var udata = {id:datauId,newPassword:newPassword};
	
	$.ajax({
		url: url + "/sys/resetPassword",
		type: "post",
		dataType: 'json',
		data:JSON.stringify(udata),
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {

			if(result.code == '0') {
			
				layer.msg(result.msg,{time:2*1000},function() {
					window.location.reload();
				});
			} else {
				isErr(result);
				window.location.reload();
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
	
});



//打开修改利润模态框
function showProfits(obj){
	datauId = $(obj).attr("data-uid");
	$(".profie").val($(obj).text());
	$('#popLayer').show();
	$('#layui-layer13').show();
}
//关闭修改利润模态框
$('.closeProfit').on("click",function(){
	$('#popLayer').hide();
	$('#layui-layer13').hide();
});
//修改利润确定按钮
$(".profitSet").on("click",function(){
	var profit = $("#profitSave").val();
	var uprofit = {id:datauId,profit:profit};
	
	$.ajax({
		url: url + "/agency/updateAgProfit",
		type: "post",
		dataType: 'json',
		data:JSON.stringify(uprofit),
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {

			if(result.code == '0') {
			
				layer.msg(result.msg,{time:2*1000},function() {
					window.location.reload();
				});
			} else {
				isErr(result);
				window.location.reload();
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
});


//获取广告主角色列表
function getRoleList(){
	$.ajax({
		url: url + "/agency/roleList/1",
		type: "post",
		//		参数需转为字符串
		//		json跨域
		dataType: 'json',
		//		contentType类型为json
		contentType: "application/json",
		useDefaultXhrHeader: false,
		//		请求头加上X-Token 
		 beforeSend: function(XMLHttpRequest) {
			//		token 为页面所获取
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
			
			if(result.code == '0') {
				var htmlr = "";													
//				console.log(result.data);
				for(var i=0;i<result.data.length;i++){
					htmlr += '<li class="cl cl1">';
						htmlr += '<a href="javascript:void(0)" data-roleId="'+result.data[i].roleId+'">'+result.data[i].roleName+'</a>';
					htmlr += '</li>';	
				}
				$(".roledropdown-menu").html(htmlr);
				
				//下拉选择获取角色id,名称
				$('.cl1').on("click",function(){
					$("#advrole").attr("data-value",$(this).children().attr("data-roleId")).text($(this).children().text());
				});
			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
}

//获取行业大类列表
function getdaleiList(){
	$.ajax({
		url: url + "/common/industryBig",
		type: "post",
		dataType: 'json',
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
			if(result.code == '0') {
				var htmlr = "";													
//				console.log(result.data);
				for(var i=0;i<result.data.length;i++){
					htmlr += '<li class="cl cl2">';
						htmlr += '<a href="javascript:void(0)" data-roleId="'+result.data[i].id+'">'+result.data[i].industryImages+'</a>';
					htmlr += '</li>';	
				}
				$(".daleidropdown-menu").html(htmlr);
				
				//下拉选择获取角色id,名称
				$('.cl2').on("click",function(){
					var bigId = $(this).children().attr("data-roleId");
					$("#advdalei").attr("data-value",bigId).text($(this).children().text());
					getxiaoleiList(bigId);
				});
			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
}

//获取行业小类列表
function getxiaoleiList(daleiid){
	$.ajax({
		url: url + "/common/industrySmall/"+daleiid,
		type: "post",
		dataType: 'json',
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
			if(result.code == '0') {
				var htmlr = "";													
//				console.log(result.data);
				$("#advxiaolei").attr("data-value","").text("请选择行业小类");
				for(var i=0;i<result.data.length;i++){
					htmlr += '<li class="cl cl3">';
						htmlr += '<a href="javascript:void(0)" data-roleId="'+result.data[i].id+'">'+result.data[i].industryImages+'</a>';
					htmlr += '</li>';	
				}
				$(".xiaoleidropdown-menu").html(htmlr);
				
				//下拉选择获取角色id,名称
				$('.cl3').on("click",function(){
					$("#advxiaolei").attr("data-value",$(this).children().attr("data-roleId")).text($(this).children().text());
				});
			} else {
				isErr(result);
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});
}


//添加广告主 （打开模态框）
function UserModal() {
	$("#advloginName1").show();
	$("#advpassWord1").show();
	$("#advpassWord21").show();
	$("#advpremium1").show();
	
	$('.addAdv').show();
	$('.updateAdv').hide();
	$("#advModal").show();
	
	$(".modal-title").text("新增广告主");
}
//新增广告主确定按钮
$('.addAdv').on("click", function() {
	$(this).attr("disabled",true).css("background","#BBBBBB");
	

	var adBrand = $('#advbrand').val(); //品牌
	var adComapyAddress = $('#advaddress').val(); //公司地址
	var adComapyName = $('#advname').val(); //公司名称
	var adComapyUrl = $('#advwwwUrl').val(); //公司网站
	var adSimple = $('#advshortName').val(); //公司简称
	var bigIndustry = $("#advdalei").text(); //行业大类
	var concat = $("#advcontacts").val(); //联系人
	var demoName = $("#advyuming").val();//域名
	var password = $("#advpassWord").val(); //密码
	var advpassWord2 = $("#advpassWord2").val(); //重复密码
	var phone = $("#advtelephone").val(); //手机号
	var profit = $("#advpremium").val(); //利润率
	var roleId = $("#advrole").attr("data-value"); //角色id
	var smallIndustry = $("#advxiaolei").text(); //行业小类
	var username = $("#advloginName").val(); //账户名
	
		
		
	if($("#advdalei").attr("data-value")==""){
		bigIndustry = "";
	}
	if($("#advxiaolei").attr("data-value")==""){
		smallIndustry = "";
	}
	if(!username || !password || !adComapyUrl || !adComapyName || !adBrand || !roleId || !bigIndustry || !smallIndustry || !concat || !demoName || !phone || !adComapyAddress || !profit) {
		layer.msg("带*都为必填项，请完善用户信息！！");
		$(this).attr("disabled",false).css("background","#4a9dd2");
		return false;
	}
	if(password != advpassWord2){
		layer.msg("两次密码输入不一致");
		$(this).attr("disabled",false).css("background","#4a9dd2");
		return false;
	}
	var param3 = "/agency/addAdUserinfoMessage";
	var method3 = "post";
	var datas3 = { adBrand: adBrand,adComapyAddress:adComapyAddress, adComapyName: adComapyName, name: name, adComapyUrl: adComapyUrl, adSimple: adSimple, bigIndustry: bigIndustry, concat:concat, demoName:demoName, password:password,phone:phone,profit:profit,roleId:roleId,smallIndustry:smallIndustry,username:username};
	getAgentMsg3(param3, method3, datas3);
//	console.log(dataResult3);
	
	layer.msg(dataResult3.msg, { time: 2 * 1000 }, function() {
		window.location.reload();
	});
});
//编辑广告主按钮（打开模态框）
function getRoleListE(obj) {
	var adUserId = $(obj).attr("data-uid");
	$.ajax({
		url: url + "/agency/editAdUserinfoMsg/" + adUserId,
		type: "post",
		dataType: 'json',
		contentType: "application/json",
		useDefaultXhrHeader: false,
		 beforeSend: function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader("X-Token", token); 
		},
		success: function(result) {
//			console.log(result);
			
			if(result.code == '0') {
//				console.log(result);
				$('#advwwwUrl').val(result.data.adComapyUrl); //公司网站
				$('#advname').val(result.data.adComapyName); //公司名称
				$('#advbrand').val(result.data.adBrand); //品牌
				$('#advshortName').val(result.data.adSimple); //公司简称
				$("#advrole").attr({ "data-roleId": result.data.roleId, "data-sysUserId": result.data.sysUserId, "data-id": result.data.id }).text(result.data.roleName);//角色
				$("#advdalei").text(result.data.bigIndustry);//行业大类
				$("#advxiaolei").text(result.data.smallIndustry);//行业小类
				$("#advyuming").val(result.data.demoName);//域名
				$("#advcontacts").val(result.data.concat); //联系人
				$("#advtelephone").val(result.data.phone); //手机号
				$('#advaddress').val(result.data.adComapyAddress); //公司地址			

				$("#advloginName1").hide();
				$("#advpassWord1").hide();
				$("#advpassWord21").hide();
				$("#advpremium1").hide();
				
				$('.addAdv').hide();
				$('.updateAdv').show();
				$("#advModal").show();
				
				$(".modal-title").text("编辑广告主");
			} else {
				layer.msg("请求失败,该数据有误!");
			}
		},
		err: function(err) {
			layer.msg("请求失败");
		}
	});

}

//编辑广告主确定按钮
$('.updateAdv').on("click", function() {
	var adBrand = $('#advbrand').val(); //品牌
	var adComapyAddress = $('#advaddress').val(); //公司地址
	var adComapyName = $('#advname').val(); //公司名称
	var adComapyUrl = $('#advwwwUrl').val(); //公司网站
	var adSimple = $('#advshortName').val(); //公司简称
	var bigIndustry = $("#advdalei").text(); //行业大类
	var concat = $("#advcontacts").val(); //联系人
	var demoName = $("#advyuming").val();//域名
	var uid = $("#advrole").attr("data-id");//广告主id
	var phone = $("#advtelephone").val(); //手机号
	var roleId = $("#advrole").attr("data-roleId"); //角色id
	var smallIndustry = $("#advxiaolei").text(); //行业小类
	var sysUserId = $("#advrole").attr("data-sysUserId");//广告主id

	var param3 = "/agency/updateAdUserinfoMsg";
	var method3 = "post";
	var datas3 = { adBrand: adBrand, adComapyAddress: adComapyAddress, adComapyName: adComapyName, adComapyUrl: adComapyUrl, adSimple: adSimple, bigIndustry:bigIndustry,concat:concat,demoName:demoName,id:uid,phone:phone,roleId:roleId,smallIndustry:smallIndustry,sysUserId:sysUserId};
	getAgentMsg3(param3, method3, datas3);
//	console.log(dataResult3);
	layer.msg(dataResult3.msg, { time: 2 * 1000 }, function() {
		window.location.reload();
	});
});
//关闭模态框
$('.close2').on("click", function() {
	$("#advModal").hide();
});


//初始化加载数据
window.onload = function() {
	param = "/agency/adUserInfoList";
	tiaozhuan(param, page, pageSize, condition);
	getRoleList();
	getdaleiList();
}